<script setup lang="ts">
import { onMounted, ref, nextTick } from "vue";
import * as echarts from 'echarts';
import { getChartList } from "@/api/chart";
import { useUserStore } from "@/stores/user";
import { ElLoading } from "element-plus";

const userStore = useUserStore();
const chartForm = ref({
  chartType: '',
  current: 0,
  goal: '',
  id: 0,
  name: '',
  pageSize: '10',
  sortFiled: '',
  sortOrder: '',
  userId: ''
});
const chartData = ref<Array<any>>([]);
const loading = ref(false);

const listMyChart = async () => {
  const userId = userStore.userId;
  chartForm.value.userId = userId;
  const ret = await getChartList(chartForm.value);
  chartData.value = ret.data.data.records;
};

const convertToValidJSON = (configStr: string) => {
  const jsonMatch = configStr.match(/\{[\s\S]*\}/);
  if (!jsonMatch) return '{}';
  let cleanedStr = jsonMatch[0];
  cleanedStr = cleanedStr.replace(/\/\*[\s\S]*?\*\/|\/\/.*/g, '');
  cleanedStr = cleanedStr.replace(/'/g, '"');
  cleanedStr = cleanedStr.replace(/(\s*)(\w+)(\s*):/g, '$1"$2"$3:');
  cleanedStr = cleanedStr.replace(/,\s*([}\]])/g, '$1');
  return cleanedStr;
};

const initChart = (chartConfig: string, domId: string) => {
  const chartDom = document.getElementById(domId);
  if (!chartDom) return;

  const loadingInstance = ElLoading.service({
    target: chartDom,
    text: '图表加载中...',
    background: 'rgba(255, 255, 255, 0.8)'
  });

  try {
    const option = JSON.parse(convertToValidJSON(chartConfig));
    const myChart = echarts.init(chartDom);
    myChart.setOption(option);
    myChart.resize();
  } catch (error) {
    console.error('图表初始化失败:', error);
    chartDom.innerHTML = `<div class="chart-error">图表渲染失败</div>`;
  } finally {
    loadingInstance.close();
  }
};
const formatGenResult = (result: string) =>{
  return result
    .replace(/\n/g, '<br>')
    .replace(/(##\s*)(.*?)(\n|$)/g, '<h3>$2</h3>')
    .replace(/(###\s*)(.*?)(\n|$)/g, '<h4>$2</h4>');
}
onMounted(async () => {
  loading.value = true;
  try {
    await listMyChart();
    await nextTick();
    chartData.value.forEach((item, index) => {
      if (item.genChart) {
        initChart(item.genChart, `chart-${index}`);
      }
    });
  } finally {
    loading.value = false;
  }
});
</script>

<template>
  <div class="data-container">
    <el-table
      :data="chartData"
      style="width: 100%"
      stripe
      v-loading="loading"
      element-loading-text="数据加载中..."
      element-loading-background="rgba(255, 255, 255, 0.8)"
    >
      <el-table-column prop="name" label="图表名称" width="180">
        <template #header>
          <span class="table-header">图表名称</span>
        </template>
      </el-table-column>

      <el-table-column prop="goal" label="分析目标" width="200">
        <template #header>
          <span class="table-header">分析目标</span>
        </template>
      </el-table-column>

      <el-table-column prop="chartType" label="图表类型" width="120" align="center">
        <template #header>
          <span class="table-header">图表类型</span>
        </template>
      </el-table-column>

      <el-table-column label="分析结果" min-width="300">
        <template #default="scope">
          <div class="analysis-result" v-html="formatGenResult(scope.row.genResult)"></div>
        </template>
      </el-table-column>

      <el-table-column prop="createTime" label="创建时间" width="180" align="center">
        <template #header>
          <span class="table-header">创建时间</span>
        </template>
      </el-table-column>

      <el-table-column label="图表预览" width="400">
        <template #default="scope">
          <div
            :id="`chart-${chartData.indexOf(scope.row)}`"
            class="chart-container"
            :class="{ 'chart-placeholder': !scope.row.genChart }"
          >
            <div v-if="!scope.row.genChart" class="empty-chart">
              <el-icon><Picture /></el-icon>
              <span>暂无图表数据</span>
            </div>
          </div>
        </template>
      </el-table-column>
    </el-table>

    <div v-if="!loading && chartData.length === 0" class="empty-data">
      <el-empty description="暂无图表数据" />
    </div>
  </div>
</template>

<style scoped lang="less">
// 设计变量
@primary-color: #409EFF;
@success-color: #67C23A;
@warning-color: #E6A23C;
@text-primary: #303133;
@text-secondary: #606266;
@border-color: #EBEEF5;
@chart-height: 320px;

.data-container {
  padding: 24px;
  background: #fff;
  border-radius: 12px;
  box-shadow: 0 6px 18px rgba(0, 0, 0, 0.04);
}

.table-header {
  font-weight: 600;
  color: @text-primary;
}

:deep(.el-table) {
  --el-table-border-color: @border-color;
  --el-table-header-bg-color: #f8fafd;

  th.el-table__cell {
    background-color: var(--el-table-header-bg-color);
  }

  .el-table__row {
    transition: background-color 0.2s ease;

    &:hover {
      background-color: #f5f7fa;

      td {
        background-color: transparent;
      }
    }
  }

  td {
    padding: 16px 0;
    color: @text-secondary;
  }
}

.analysis-result {
  line-height: 1.8;
  padding: 12px;
  background: #f8fafd;
  border-radius: 6px;

  h3 {
    color: @primary-color;
    margin: 8px 0 12px;
    font-size: 16px;
    font-weight: 600;
  }

  h4 {
    color: @success-color;
    margin: 6px 0 10px;
    font-size: 14px;
    font-weight: 500;
  }

  p {
    margin-bottom: 8px;
    color: @text-secondary;
  }
}

.chart-container {
  height: @chart-height;
  border-radius: 8px;
  overflow: hidden;
  transition: box-shadow 0.3s ease;
  position: relative;

  &:hover {
    box-shadow: 0 4px 12px rgba(0, 0, 0, 0.08);
  }

  &.chart-placeholder {
    background: #f8fafd;
    display: flex;
    align-items: center;
    justify-content: center;
  }

  .empty-chart {
    text-align: center;
    color: @text-secondary;

    .el-icon {
      font-size: 48px;
      color: #C0C4CC;
      margin-bottom: 12px;
    }

    span {
      display: block;
      font-size: 14px;
    }
  }
}

.empty-data {
  padding: 60px 0;
  text-align: center;
  background: #fff;
  border-radius: 12px;
}

@media (max-width: 1200px) {
  .chart-container {
    height: 280px;
  }
}

@media (max-width: 992px) {
  .analysis-result {
    h3 { font-size: 14px; }
    h4 { font-size: 13px; }
    p { font-size: 12px; }
  }

  .chart-container {
    height: 240px;
  }
}

@media (max-width: 768px) {
  .data-container {
    padding: 16px;
  }

  :deep(.el-table) {
    td, th {
      padding: 12px 8px;
    }
  }

  .chart-container {
    height: 200px;
  }
}
</style>
